package com.soshalboard.remote;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.soshalboard.remote.exceptions.RemoteException;
import com.soshalboard.remote.interfaces.APIInterface;
import com.soshalboard.remote.interfaces.domain.Condition;
import com.soshalboard.utils.Constants;
import com.soshalboard.utils.CreateExcel;
import com.twolattes.json.Marshaller;
import com.twolattes.json.TwoLattes;

/**
 * This class extends HttpServlet abstract class, to override its various
 * methods related to various HTTP methods.
 * 
 * @author Ankur Singh
 * 
 */
public class APIv1Servlet extends HttpServlet {
	private static final long serialVersionUID = -5269290667262238189L;
	private static Log log = LogFactory.getLog(APIv1Servlet.class);
	private static ServletContext context;
	private static ApplicationContext applicationContext;
	private static String realPath;
	

	/**
	 * To initialize servlet and Springs applicationContext.xml
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		System.out.println("servlet initializaed");
		super.init(config);
		context = config.getServletContext();
		applicationContext = WebApplicationContextUtils
				.getWebApplicationContext(context);
		realPath = getServletContext().getRealPath("/json");
		context = config.getServletContext();

	}

	/*
	 * Overrided method of javax.servlet.http.HttpServlet to Called by the
	 * server (via the service method) to allow a servlet to handle a GET
	 * request.
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) throws ServletException,
			IOException {

		APIInterface api = (APIInterface) applicationContext.getBean("restAPI");
		CreateExcel excel = (CreateExcel) applicationContext.getBean("createExcel");
		
		String action = getAction(httpServletRequest);
		// PrintWriter out = httpServletResponse.getWriter();
		ServletOutputStream outPutStream = httpServletResponse
				.getOutputStream();
		log.info("In APIv1Servlet.java:: got action " + action);
		//ErrorResponse response = null;
		HttpSession httpSession = httpServletRequest.getSession(true);
		String reportType = httpServletRequest.getParameter("reportType");

		Condition condition = getCondition(httpServletRequest);
		condition.setReportType(action);

		try {
		
//			if ("excel".equalsIgnoreCase(action)) {
//
//
//				String viewType = httpServletRequest.getParameter("view");
//				if ("ExcelDownload".equalsIgnoreCase(viewType)) {
//					HSSFWorkbook workBook = null;
//					
//					if (null != reportType
//							&& reportType
//									.equalsIgnoreCase(Constants.REPORT_TYPE_REVENUE)) {
//						String responseString = api.getRevenueReport(condition);
//
//						String[] respArray = responseString.split("&");
//						
//						String [] results = respArray[1].split("\\*");
//						
//						List <List> dataList = new ArrayList <List>();
//						
//						for (String result:results) {
//							String[] data = result.split(",");
//							List<String> listData = Arrays.asList(data);
//							dataList.add(listData);
//						}
//
//						HSSFWorkbook workbook = excel.getExcelWorkBook(respArray[0], dataList, "", "", "RevenueReport -" + condition.getReportDateFrom());
//						httpServletResponse.setHeader("Content-disposition",
//								"inline;fileName=" + "RevenueReport-" + condition.getCountry() + condition.getCircle() + condition.getReportDateFrom());
//						workBook.write(outPutStream);
//						outPutStream.close();
//						return;
//					}
//					
//					String operatorName = httpServletRequest
//							.getParameter("operator");
//					String type = httpServletRequest.getParameter("type");
//					String circleType = httpServletRequest
//							.getParameter("circletype");
//					if ("daily".equalsIgnoreCase(type)) {
//						String startDate = httpServletRequest
//								.getParameter("startDate");
//						String endDate = httpServletRequest
//								.getParameter("endDate");
//						if (!"".equals(endDate)) {
//							type = "dailyRange";
//						}
//						workBook = api.getExcelReport(operatorName, "", "",
//								changeDateFormat(startDate),
//								changeDateFormat(endDate), "", "", reportType,
//								type, circleType,
//								httpServletRequest.getParameter("countryName"));
//						
//						
//					} else if ("hourly".equalsIgnoreCase(type)) {
//						String startHour = httpServletRequest
//								.getParameter("startHour");
//						String endHour = httpServletRequest
//								.getParameter("endHour");
//						String requestDate = httpServletRequest
//								.getParameter("startDate");
//						if (!"".equals(endHour)) {
//							type = "hourlyRange";
//						}
//						workBook = api.getExcelReport(operatorName, startHour,
//								endHour, changeDateFormat(requestDate), "", "",
//								"", reportType, type, circleType,
//								httpServletRequest.getParameter("countryName"));
//					} else if ("monthly".equalsIgnoreCase(type)) {
//						String startMonth = httpServletRequest
//								.getParameter("startMonth");
//						String endMonth = httpServletRequest
//								.getParameter("endMonth");
//						if (!"".equals(endMonth)) {
//							type = "monthlyRange";
//						}
//						workBook = api.getExcelReport(operatorName, "", "", "",
//								"", startMonth, endMonth, reportType, type,
//								circleType,
//								httpServletRequest.getParameter("countryName"));
//					}
//					if (workBook == null) {
//						httpServletResponse
//								.sendRedirect("/report/jsp/mis.jsp?msg=DATA NOT AVAILABLE IN DB");
//						outPutStream.close();
//						return;
//					}
//					httpServletResponse
//							.setContentType("application/vnd.ms-excel");
//					DateFormat dateFormat = new SimpleDateFormat("dd_MM_yyyy");
//					Date date = new Date();
//					httpServletResponse.setHeader("Content-disposition",
//							"inline;fileName=" + dateFormat.format(date));
//					workBook.write(outPutStream);
//					outPutStream.close();
//				} else if ("ViewReport".equalsIgnoreCase(viewType)) {
//					
//					if (null != reportType
//							&& reportType
//									.equalsIgnoreCase(Constants.REPORT_TYPE_REVENUE)) {
//						String responseString = api.getRevenueReport(condition);
//
//						String[] respArray = responseString.split("&");
//						httpSession.setAttribute("tableHeading", respArray[0]);
//						httpSession.setAttribute("tableValues", respArray[1]);
//						httpServletResponse
//								.sendRedirect("/report/jsp/tableView.jsp?");
//						return;
//					} 
//					
//					if (null != reportType
//							&& reportType
//									.equalsIgnoreCase(Constants.REPORT_TYPE_MOST_ACTIVE)) {
//						String responseString = api.getMostActiveReport(condition);
//
//						String[] respArray = responseString.split("&");
//						httpSession.setAttribute("tableHeading", respArray[0]);
//						httpSession.setAttribute("tableValues", respArray[1]);
//						httpServletResponse
//								.sendRedirect("/report/jsp/tableView.jsp?");
//						return;
//					}					
//					
//					if (null != reportType
//							&& reportType
//									.equalsIgnoreCase(Constants.REPORT_TYPE_FONEIM_USSD)) {
//						String responseString = api.getFoneIMUSSDReport(condition);
//
//						String[] respArray = responseString.split("&");
//						httpSession.setAttribute("tableHeading", respArray[0]);
//						httpSession.setAttribute("tableValues", respArray[1]);
//						httpServletResponse
//								.sendRedirect("/report/jsp/tableView.jsp?");
//						return;
//					}										
//					
//					String operatorName = httpServletRequest
//							.getParameter("operator");
//					String type = httpServletRequest.getParameter("type");
//					String circleType = httpServletRequest
//							.getParameter("circletype");
//					String responseString = "";
//					if ("daily".equalsIgnoreCase(type)) {
//						String startDate = httpServletRequest
//								.getParameter("startDate");
//						String endDate = httpServletRequest
//								.getParameter("endDate");
//						if (!"".equals(endDate)) {
//							type = "dailyRange";
//						}
//						responseString = api.getHtmlReport(operatorName, "",
//								"", changeDateFormat(startDate),
//								changeDateFormat(endDate), "", "", reportType,
//								type, circleType,
//								httpServletRequest.getParameter("countryName"));
//					} else if ("hourly".equalsIgnoreCase(type)) {
//						String startHour = httpServletRequest
//								.getParameter("startHour");
//						String endHour = httpServletRequest
//								.getParameter("endHour");
//						String requestDate = httpServletRequest
//								.getParameter("startDate");
//						if (!"".equals(endHour)) {
//							type = "hourlyRange";
//						}
//						responseString = api.getHtmlReport(operatorName,
//								startHour, endHour,
//								changeDateFormat(requestDate), "", "", "",
//								reportType, type, circleType,
//								httpServletRequest.getParameter("countryName"));
//					} else if ("monthly".equalsIgnoreCase(type)
//							|| "monthlyRange".equalsIgnoreCase(type)) {
//						String startMonth = httpServletRequest
//								.getParameter("startMonth");
//						String endMonth = httpServletRequest
//								.getParameter("endMonth");
//						if (!"".equals(endMonth)) {
//							type = "monthlyRange";
//						}
//						responseString = api.getHtmlReport(operatorName, "",
//								"", "", "", startMonth, endMonth, reportType,
//								type, circleType,
//								httpServletRequest.getParameter("countryName"));
//					}
//					if ("".equalsIgnoreCase(responseString)) {
//						httpServletResponse
//								.sendRedirect("/report/jsp/mis.jsp?msg=DATA NOT AVAILABLE IN DB*");
//						outPutStream.close();
//						return;
//					}
//					String[] respArray = responseString.split("&");
//					httpSession.setAttribute("tableHeading", respArray[0]);
//					httpSession.setAttribute("tableValues", respArray[1]);
//					httpServletResponse
//							.sendRedirect("/report/jsp/tableView.jsp?");
//				}
//
//			} else if ("operatorList".equalsIgnoreCase(action)) {
//				String operatorList = api.getOperatorList(reportType);
//				outPutStream.println(operatorList);// CountryList
//			} else if ("CountryList".equalsIgnoreCase(action)) {
//				String countryList = api.getCountryList(httpServletRequest
//						.getParameter("operatorName"));
//				outPutStream.println(countryList);// CountryList
//			} else if ("login".equalsIgnoreCase(action)) {
//				String userID = httpServletRequest.getParameter("userID");
//				String password = httpServletRequest.getParameter("password");
//				Integer result = api.authenticate(userID, password);
//				if (result == 0) {
//					httpServletResponse
//							.sendRedirect("/report/jsp/login.jsp?msg=Invalid userID or Password*");
//				} else {
//					httpSession.setAttribute("userID", userID);
//					httpServletResponse
//							.sendRedirect("/report/jsp/mis.jsp?msg=Please Select Filters");
//				}
//			} else if ("dashboard".equalsIgnoreCase(action)) {
//				Dashboard dashboard = api.getDashboard();
//				
//				String result = dashboard.toJson();
//				outPutStream.print(result);				
//				return;
//			} else {
//				outPutStream.print("400");
//			}

		} catch (RemoteException se) {
//			Marshaller<ErrorResponse> br = TwoLattes
//					.createMarshaller(ErrorResponse.class);
//			response = new ErrorResponse(se.getMessage(), se.getCode());

			if (se.getCode() != 1 || se.getCode() != 2 || se.getCode() != 10) {
				log.error("", se);
			} else {
				log.error(se.getMessage());
			}
			// out.print("500");
		} catch (Exception e) {
			outPutStream.print("Error occured at server side");
			outPutStream.close();
			e.printStackTrace();
//			Marshaller<ErrorResponse> br = TwoLattes
//					.createMarshaller(ErrorResponse.class);
//			response = new ErrorResponse("Error: " + e.getMessage(),
//					ErrorResponse.ERROR_UNKNOWN);
			log.error("", e);
			// out.print("500");
		}
	}

	private Condition getCondition(HttpServletRequest httpServletRequest) {

		Condition condition = new Condition();
		condition.setOperator(httpServletRequest.getParameter("operator"));
		condition.setCountry(httpServletRequest.getParameter("countryName"));

		String type = httpServletRequest.getParameter("type");
		condition.setReportDuration(type);
		condition.setCircle(httpServletRequest.getParameter("circletype"));
		condition.setReportDateFrom(changeDateFormat(httpServletRequest
				.getParameter("startDate")));
		condition.setReportDateTo(changeDateFormat(httpServletRequest.getParameter("endDate")));

		if (null != type
				&& type.equalsIgnoreCase(Constants.REPORT_DURATION_TYPE_HOUR)) {
			condition.setReportType(type);
			condition.setReportDurationFrom(httpServletRequest
					.getParameter("startHour"));
			condition.setReportDurationTo(httpServletRequest
					.getParameter("endHour"));
		}

		if (null != type
				&& type.equalsIgnoreCase(Constants.REPORT_DURATION_TYPE_MONTH)) {
			condition.setReportType(type);			
			condition.setReportDurationFrom(httpServletRequest
					.getParameter("startMonth"));
			condition.setReportDurationTo(httpServletRequest
					.getParameter("endMonth"));
		}

		if (null != type
				&& type.equalsIgnoreCase(Constants.REPORT_DURATION_TYPE_DAY)) {
			condition.setReportType(type);			
			condition.setReportDurationFrom(changeDateFormat(httpServletRequest
					.getParameter("startDate")));
			condition.setReportDurationTo(changeDateFormat(httpServletRequest
					.getParameter("endDate")));
		}		
		
		return condition;

	}

	/*
	 * Called by the server (via the service method) to allow a servlet to
	 * handle a POST request.
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) throws ServletException,
			IOException {
		doGet(httpServletRequest, httpServletResponse);
	}

	/*
	 * Extract and Returns Action attributes from HttpServletRequest URL.
	 */
	private String getAction(HttpServletRequest httpServletRequest) {
		String url = httpServletRequest.getRequestURL().toString();
		System.out
				.println("Remote Api::Request from the Remote client on URL :"
						+ url + "?" + httpServletRequest.getQueryString());
		log.info("Remote Api::Request from the Remote client on URL :" + url
				+ "?" + httpServletRequest.getQueryString());
		return url.substring(url.lastIndexOf("/") + 1);
	}

	private String changeDateFormat(String strDate) {
		try {
			
			if (null==strDate || "".equals(strDate)){
				return null;
			}
			SimpleDateFormat sdfSource = new SimpleDateFormat("MM-dd-yyyy");
			Date date = sdfSource.parse(strDate);
			SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
			strDate = sdfDestination.format(date);
			log.info("Converted date is : " + strDate);
			return strDate;
		} catch (ParseException pe) {
			return null;
		}
	}

}